<?php

/* Classe articleManager */

require_once 'Article.php';
require_once 'Base.php';

class ArticleManager
{
    private $_bdd;

    public function __construct(PDO $db) {
        $this->_bdd = $db;
    }

    // Renvoi l'id du dernier inscrit
    public function lastInsertedId() {
        $q = $this->_bdd->query('SELECT MAX(id) FROM articles');
        return $q->fetch();
    }

    // Ajoute un article
    public function add(Article $a) {
        $q = $this->_bdd->prepare("INSERT INTO articles (user, name, description, prix, categorie, ville, couleur) VALUES (:usr, :name, :description, :prix, :categorie, :ville, :couleur)");
        $q->bindValue(':usr', $a->getUser(), PDO::PARAM_STR);
        $q->bindValue(':name', $a->getName(), PDO::PARAM_STR);
        $q->bindValue(':description', $a->getDescription(), PDO::PARAM_STR);
        $q->bindValue(':prix', $a->getPrix(), PDO::PARAM_INT);
        $q->bindValue(':categorie', $a->getCategorie(), PDO::PARAM_STR);
        $q->bindValue(':ville', $a->getVille());
        $q->bindValue(':couleur', $a->getCouleur());
        $q->execute();
        $a->setId($this->lastInsertedId());
    }

    // Supprime un article
    public function delete($id) {
        $q = $this->_bdd->prepare('DELETE FROM articles WHERE id = :id');
        $q->bindValue(':id', $id);
        $q->execute();
    }

    // Charge les infos d'un article à partir de son id
    public function get($id) {
        $q = $this->_bdd->prepare('SELECT * FROM articles WHERE id = :id');
        $q->bindValue(':id', $id, PDO::PARAM_INT);
        $q->execute();
        $data = $q->fetch(PDO::FETCH_ASSOC);
        if($data != null)
            return new Article($data);
        else
            return false;
    }

    // Retourne la liste des articles
    public function getList() {
        $articles = array();
        $q = $this->_bdd->query('SELECT * FROM articles');
        while($data = $q->fetch(PDO::FETCH_ASSOC)) {
            $articles[] = new Article($data);
        }
        return $articles;
    }

    public function execRequete($requete){
	$articles = array();
        $q = $this->_bdd->query($requete);
        while($data = $q->fetch(PDO::FETCH_ASSOC)) {
            $articles[] = new Article($data);
        }
        return $articles;
    }
}

?>
